import DataType from "utils/DataType";

const JsonUtils = {
	toString(json = {}) {
		if (DataType.isObject(json) || DataType.isArray(json)) {
			return JSON.stringify(json);
		}
	},

	toJson(string = "") {
		if (DataType.isString(string)) {
			return JSON.parse(string);
		}
	},

	toFormData(json = {}) {
		if (DataType.isObject(json)) {
			let string = "?";
			Object.keys(json).forEach(key => {
				string += key + "=" + json[key] + "&";
			});
			return string.slice(0, string.lastIndexOf("&"));
		}
	},

	fromFormData(string = "") {
		if (DataType.isString(string)) {
			if (string.includes("?")) {
				string = string.replace("?", "");
			}
			string = string.replace("=", ":").replace("&", ",");
			return JSON.parse(string);
		}
	}
};

export default JsonUtils;
